package net;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class GameClient implements Runnable{
	Socket client;
	public Thread clientThread;
	public static String ip;
    public ObjectOutputStream oos;
    public ObjectInputStream ois;
	
	public GameClient(String _ip){
		ip = _ip;
		clientThread = new Thread(this);
		clientThread.start();
	}

	public void sendMessage(Message _msg){
		try{
			oos.writeObject(_msg);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void receiveMessage(Message _msg){
		System.out.println("Server: " + _msg);
	}
	
	public void run(){
		try {
			if(client != null)
			System.out.println("client: " + client.getReceiveBufferSize());
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(client == null){
			try{
				client = new Socket(ip, 9999);
				oos = new ObjectOutputStream(client.getOutputStream());
				ois = new ObjectInputStream(client.getInputStream());
			}catch(Exception e){
				e.printStackTrace();
			}
		} else {
			while(Thread.currentThread().equals(clientThread)){
				try {
					Message tmp = (Message)ois.readObject();
					System.out.println("tmpServer: " + tmp);
					if(tmp != null){
						receiveMessage(tmp);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
